package com.csvw.skr.newTask.controller;

import com.csvw.skr.basic.core.JobType;
import com.csvw.skr.basic.entity.User;
import com.csvw.skr.console.service.UserService;
import com.csvw.skr.newTask.core.VisitItem;
import com.csvw.skr.newTask.core.VisitMissionReportDto;
import com.csvw.skr.newTask.core.VisitPlanDto;
import com.csvw.skr.newTask.entity.PlanProblem;
import com.csvw.skr.newTask.entity.visit.Mission;
import com.csvw.skr.newTask.entity.visit.PlanMission;
import com.csvw.skr.newTask.entity.visit.VisitPlan;
import com.csvw.skr.newTask.service.VisitService;


import com.google.common.collect.Lists;
import com.webonn.frame.core.OAuthPrincipal;
import com.webonn.frame.core.Pagination;
import com.webonn.frame.util.APIResultBuilder;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.security.PermitAll;
import javax.ws.rs.*;
import javax.ws.rs.core.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * permitAll，会给没有登录的用户适配一个AnonymousAuthenticationToken，设置到SecurityContextHolder，
 方便后面的filter可以统一处理authentication。
 注解@Produces用于定义方法的响应实体的数据类型，可以定义一个或多个，同时可以为每种类型定义质量因素（qualityfactor）
 */
@PermitAll
@RestController
@RequestMapping(value="/task/newVisit")
@Produces({MediaType.APPLICATION_JSON + "; charset=UTF-8", MediaType.TEXT_HTML + "; charset=UTF-8"})
public class VisitController {
    private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(VisitController.class);

    private static  String CURRENT_USER = "13429";
    @Autowired
    private VisitService visitService;
    @Autowired
    private UserService userService;
    /**
     * 根据type类型查询可选任务和必选任务 csvw_skr_task_visit_mission
     * 1：必做任务，2：可选任务
     * @param type
     * @return
     */
    @RequestMapping(value="/mission/type/{type}", method=RequestMethod.GET)
    public  Response queryTaskByType(@PathVariable int type){
        //判断参数是否异常
        if(type != 1 && type != 2){
            LOGGER.error("----------------参数为"+type+",异常----------------------");
            return APIResultBuilder.INVALID_REQUEST("参数异常");
        }
        List missions = visitService.queryTaskByType(type);
        if(missions != null){
            return APIResultBuilder.OK(missions);
        }else {
            return APIResultBuilder.NOT_FOUND("查询失败");
        }
    }

    /**
     * 根据missionId查询检查表
     * @param missionId
     * @return
     */
    @RequestMapping(value="/mission/{missionId}/check", method=RequestMethod.GET)
    public Response getMissionCheck(@PathVariable String missionId){
        List result = visitService.getMissionCheckList(missionId);
        if(result != null){
            return  APIResultBuilder.OK(result);
        }else{
            return APIResultBuilder.NOT_FOUND("查询失败");
        }
    }

    /**
     * 创建自定义走访项
     * @param mission
     * @return
     */
    @RequestMapping(value="/mission", method=RequestMethod.POST)
    public Response createMission( Mission mission){
        //设置创建自定义走访项的人
        mission.setPublisher(CURRENT_USER);
        Mission entity = visitService.addMission(mission);
        if(entity != null){
            return APIResultBuilder.OK(entity);
        }else {
            return APIResultBuilder.UnprocesableEntity("添加失败");
        }
    }

    /**
     * Put请求用来修改更改资源
     * @param missionId
     * @param entity
     * @return
     */
    @RequestMapping(value="/mission/{missionId}", method=RequestMethod.PUT)
    public Response modifyMission(@PathVariable String missionId,Mission entity){
        //非空判断
        if(entity == null || !missionId.equalsIgnoreCase(entity.getId())){
            return APIResultBuilder.INVALID_REQUEST("无效的请求");
        }
        Mission mission = visitService.modifyMission(entity);
        if(mission != null){
            return APIResultBuilder.OK(mission);
        }else {
            return APIResultBuilder.UnprocesableEntity("更新失败");
        }
    }

    /**
     * 删除任务
     * @param missionId
     * @return
     */
    @RequestMapping(value="/mission/{missionId}", method=RequestMethod.DELETE)
    public Response deleteMission(@PathVariable String missionId){
        //TODO缺少任务存在、权限校验
        Mission mission = visitService.deleteMission(missionId);
        if(mission != null){
            return APIResultBuilder.OK(mission);
        }else {
            return APIResultBuilder.UnprocesableEntity("删除失败");
        }
    }

    /**
     * 新建走访计划
     * @param visitPlanDto
     * @return
     */
    @RequestMapping(value="/plan", method=RequestMethod.POST)
    public Response createVisitPlan(VisitPlanDto visitPlanDto){
        //根据用户id获取当前用户信息
        User user = userService.getUser(CURRENT_USER);
        //只有小区经理才可以创建店访计划
        if(!JobType.BUSINESS_MANAGER.equalsIgnoreCase(user.getJob())){
            return APIResultBuilder.Forbidden("只有小区经理可以创建店访计划");
        }
        //设置店访计划的信息
        VisitPlan visitPlan = visitPlanDto.getVisitPlan();
        visitPlan.setBusinessManager(user.getEmpno());
        String area = user.getOrganization();
        visitPlan.setArea(area);
        visitPlan.setRbo(area.substring(0, area.indexOf("-")));
        visitPlan.setCommercial(area.substring(0, area.lastIndexOf("-")));
        visitPlanDto.setVisitPlan(visitPlan);
        VisitPlan result = visitService.createVisitPlan(visitPlanDto);
        if(result != null){
            return  APIResultBuilder.CREATED(result);
        }else {
            return APIResultBuilder.UnprocesableEntity("添加失败");
        }
    }

    @RequestMapping(value="/plan/{visitId}", method=RequestMethod.GET)
    public Response getVisitPlan(@PathVariable String visitId) {
        Map result = visitService.getVisitPlanInfo(visitId);
        if (result != null) {
            return APIResultBuilder.OK(result);
        } else {
            return APIResultBuilder.NOT_FOUND("获取失败");
        }
    }

    /**
     * 更改计划
     * @param visitId
     * @param visitPlanDto
     * @return
     */
    @RequestMapping(value="/plan/{visitId}", method=RequestMethod.PUT)
    public Response updateVisitPlan(@PathVariable String visitId, VisitPlanDto visitPlanDto){
        VisitPlan old = visitPlanDto.getVisitPlan();
        //判断计划是否已经提交
        if(old.getStatus() > 20){
            return APIResultBuilder.Forbidden("已提交的例会计划不能编辑");
        }
        VisitPlan vp = visitPlanDto.getVisitPlan();
        vp.setId(visitId);
        visitPlanDto.setVisitPlan(vp);
        VisitPlan result = visitService.updateVisitPlan(visitPlanDto);
        if(result != null){
            return APIResultBuilder.CREATED(result);
        }else {
            return APIResultBuilder.UnprocesableEntity("操作失败");
        }
    }

    /**
     * 查询店访计划列表
     * @param start
     * @param limit
     * @param uriInfo
     * @return
     */
    @RequestMapping(value = "/plan",method = RequestMethod.GET)
    public Response queryVisitPlan(int start, int limit, UriInfo uriInfo){
        MultivaluedMap<String,String> filterSerch = uriInfo.getPathParameters();
        Pagination result = visitService.queryVisitPlan(CURRENT_USER,start,limit,filterSerch);
        if (result != null){
            return APIResultBuilder.OK(result);
        }else {
            return APIResultBuilder.NOT_FOUND("未查询到数据");
        }
    }

    /**
     * 删除店访计划
     * @param visitId
     * @return
     */
    @RequestMapping(value = "/plan/{visitId}",method = RequestMethod.DELETE)
    public Response deleteVisitPlan(@PathVariable String visitId){
        //先判断删除的计划是否存在
        VisitPlan  visitPlan = visitService.getVisitPlan(visitId);
        if(visitPlan == null){
            return APIResultBuilder.Gone("删除的店访计划不存在");
        }
        if(visitPlan.getStatus() > 20){
            return APIResultBuilder.Forbidden("已经提交的售前店访计划不能删除");
        }
        boolean result = visitService.deleteVisitPlan(visitId);
        if(result){
            return APIResultBuilder.OK(result);
        }else {
            return APIResultBuilder.UnprocesableEntity(" 删除店访计划失败");
        }
    }

    /**
     * 撤回店访报告
     * @param visitId
     * @return
     */
    @RequestMapping(value = "/plan/{visitId}/report/revocation",method = RequestMethod.GET)
    public Response revocationVisitReport(@PathVariable String visitId){
        VisitPlan  visitPlan = visitService.getVisitPlan(visitId);
        if (visitPlan.getStatus() > 21) {
            return APIResultBuilder.Forbidden("已提交的售前店访计划不能撤回");
        }
        boolean result = visitService.revocationVisitReport(visitId);
        if(result){
            return APIResultBuilder.OK(result);
        }else {
            return APIResultBuilder.UnprocesableEntity("撤回售前店访报告失败");
        }
    }

    /**查询店访报告列表
     *
     * @param start
     * @param limit
     * @param uriInfo
     * @return
     */
    @RequestMapping(value = "/report",method = RequestMethod.GET)
    public Response queryVisitReport(@QueryParam("start") int start,@DefaultValue("20") @QueryParam("limit") int limit,@Context UriInfo uriInfo){
        MultivaluedMap<String,String> filterSearch = uriInfo.getQueryParameters();
        Pagination result = visitService.queryVisitReport(CURRENT_USER,start,limit,filterSearch);
        if(result != null){
            return APIResultBuilder.OK(result);
        }else {
            return APIResultBuilder.NOT_FOUND("未查询到数据");
        }
    }

    /**
     * 审批店访报告
     * @param visitId
     * @param doc
     * @return
     */
    @RequestMapping(value = "/plan/{visitId}/result",method = RequestMethod.PUT)
    public Response approvalVisitPlan( @PathVariable String visitId, Map<String, Object> doc){
        if(doc == null || !doc.containsKey("approvealDescription")|| !doc.containsKey("pass")){
            return APIResultBuilder.INVALID_REQUEST("非法参数");
        }
        User user = userService.getUser(CURRENT_USER);
        if (!JobType.COMMERCIAL_DIRECTOR.equalsIgnoreCase(user.getJob()) && !JobType.SALES_VICE_MANAGER.equalsIgnoreCase(user.getJob())) {
            return APIResultBuilder.Forbidden("只有商务总监或副总才具有审批权限");
        }
        VisitPlan old = visitService.getVisitPlan(visitId);
        if(old.getStatus() != 31){
            return APIResultBuilder.Forbidden("只有待审批售前店访报告才可以审批");
        }
        //getOrDefault方法是从java1.8中的方法
        VisitPlan result = visitService.approvalVisitReport(visitId, (String) doc.getOrDefault("approvalDescription", ""), (boolean) doc.getOrDefault("pass", false));
        if(result != null){
            return APIResultBuilder.CREATED(result);
        }else {
            return APIResultBuilder.NOT_FOUND("操作失败");
        }
    }

    /**
     * 获取店访任务报告详情
     * @param visitId
     * @return
     */
    @RequestMapping(value = "/plan/{visitId}/report",method = RequestMethod.GET)
    public Response getVisitReportInfo(@PathVariable String visitId){
        Map result = visitService.getVisitReportInfo(visitId);
        if(result != null){
            return APIResultBuilder.CREATED(result);
        }else {
            return APIResultBuilder.NOT_FOUND("操作失败");
        }
    }

    /**
     * 提交店访报告
     * @param visitId
     * @return
     */
    @RequestMapping(value = "/plan/{visitId}/report",method = RequestMethod.PUT)
    public  Response submitVisitPlanReport(@PathVariable String visitId){
        VisitPlan visitPlan = visitService.getVisitPlan(visitId);
        if(visitPlan == null){
            return APIResultBuilder.Gone("该售前店访任务不存在，无法完成报告提交");
        }
        if(visitPlan.getStatus() < 21){
            return APIResultBuilder.Forbidden("未提交的售前店访计划不能提交报告");
        }
        VisitPlan result = visitService.submtVisitReport(visitId);
        if(result != null){
            return APIResultBuilder.CREATED(result);
        }else {
            return APIResultBuilder.UnprocesableEntity("操作失败");
        }
    }

    /**
     * 获取店访任务检查表检查项
     * @param visitId
     * @param missionId
     * @return
     */
    @RequestMapping(value = "/plan/{visitId}/mission/{missionId}/check",method = RequestMethod.GET)
    public Response getPlanMissionCheck(@PathVariable String visitId, @PathVariable String missionId) {
        if ("0".equals(missionId)) return APIResultBuilder.CREATED(Lists.newArrayList());

        Mission mission = visitService.getMission(missionId);
        if (!mission.isChecklist()) {
            return APIResultBuilder.INVALID_REQUEST("该任务没有检查表");
        }
        List result = visitService.getPlanMissionCheck(visitId, missionId);
        if (result != null) {
            return APIResultBuilder.CREATED(result);
        } else {
            return APIResultBuilder.NOT_FOUND("该任务未找到检查表");
        }
    }

    /**
     * 提交店访任务检查表
     * @param visitId
     * @param missionId
     * @param checkItemIds
     * @return
     */
    @RequestMapping(value = "/plan/{visitId}/mission/{missionId}/check",method = RequestMethod.POST)
    public Response reportPlanMissionCheck(@PathVariable String visitId,@PathVariable String missionId,List<String> checkItemIds){
        if(checkItemIds == null || checkItemIds.size() < 1){
            return APIResultBuilder.INVALID_REQUEST("非法参数");
        }
        Map<String,Object> result = new HashMap<>();
        result.put("result", visitService.reportPlanMissionCheck(visitId, missionId, checkItemIds));
        return APIResultBuilder.CREATED(result);
    }

    /**
     * 修改店访任务结果
     * @param visitId
     * @param missionId
     * @param visitMissionReportDto
     * @return
     */
    @RequestMapping(value = "/plan/{visitId}/mission/{missionId}",method = RequestMethod.PUT)
    public Response updatePlanMissionReport(String visitId, String missionId, VisitMissionReportDto visitMissionReportDto){
        if(visitMissionReportDto == null || visitMissionReportDto.getPlanMission() == null){
            return  APIResultBuilder.INVALID_REQUEST("非法参数");
        }
        PlanMission result = visitService.updatePlanMissionReport(visitMissionReportDto);
        if(result != null){
            return APIResultBuilder.CREATED(result);
        }else {
            return APIResultBuilder.NOT_FOUND("操作失败");
        }
    }

    /**
     * 获取店访任务结果
     * @param visitId
     * @param missionId
     * @return
     */
    @RequestMapping(value = "/plan/{visitId}/mission/{missionId}",method = RequestMethod.GET)
    public Response getPlanMissionInfo(@PathVariable String visitId,@PathVariable String missionId){
        Map result = visitService.getMissionInfo(visitId,missionId);
        if(result != null){
            return APIResultBuilder.OK(result);
        }else {
            return APIResultBuilder.NOT_FOUND("操作失败");
        }
    }

    /**
     * 新增店访任务结果
     * @param visitId
     * @param missionId
     * @param visitMissionReportDto
     * @return
     */
    @RequestMapping(value = "/plan/{visitId}/mission/{missionId}",method = RequestMethod.POST)
    public Response newPlanMissionReport(@PathVariable String visitId, @PathVariable String missionId, VisitMissionReportDto visitMissionReportDto) {
        if (visitMissionReportDto == null || visitMissionReportDto.getPlanMission() == null) {
            return APIResultBuilder.INVALID_REQUEST("非法参数");
        }
        PlanMission result = visitService.newPlanMissionReport(visitMissionReportDto);
        if (result != null) {
            return APIResultBuilder.CREATED(result);
        } else {
            return APIResultBuilder.NOT_FOUND("操作失败");
        }
    }

    /**
     *店访走访项结果提交(报告中新增走访项任务)
     * @param planId
     * @param visitItem
     * @return
     */
    @RequestMapping(value = "/plan/{planId}/item",method = RequestMethod.POST)
    public Response newPlanItem(@PathVariable String planId,VisitItem visitItem){
        if(visitItem == null|| visitItem.getPlanId() == null){
            return APIResultBuilder.INVALID_REQUEST("非法参数");
        }else if (visitItem.getFinish() != 1 && visitItem.getPlanProblem() == null){
            return APIResultBuilder.INVALID_REQUEST("非法参数");
        }
        PlanMission result = visitService.createPlanItem(visitItem);
        if(result != null){
            return APIResultBuilder.CREATED(result);
        }else {
            return APIResultBuilder.NOT_FOUND("操作失败");
        }
    }

    /**
     * 店访上次走访问题解决
     * @param planId
     * @param problemId
     * @param planProblem
     * @return
     */
    @RequestMapping(value = "/plan/{planId}/item/{problemId}/result",method = RequestMethod.POST)
    public Response checkPlanProblem(@PathVariable String planId, @PathVariable String problemId, PlanProblem planProblem) {
        if (planProblem == null || planProblem.getId() == null || !planProblem.getId().equalsIgnoreCase(problemId)) {
            return APIResultBuilder.INVALID_REQUEST("非法参数");
        }
        PlanProblem result = visitService.checkPreviousProblem(problemId,planProblem.getCheckResult(),planProblem.getCheckPlanId(),planProblem.getPass());
        if(result != null){
            return APIResultBuilder.CREATED(result);
        }else {
            return APIResultBuilder.NOT_FOUND("操作失败");
        }
    }
}